package org.example.task.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.task.mapper.UserMapper;
import org.example.task.model.dto.PageDTO;
import org.example.task.model.po.LoginUser;
import org.example.task.model.po.User;
import org.example.task.model.query.UserPageQuery;
import org.example.task.model.vo.R;
import org.example.task.model.vo.user.UserPageVO;
import org.example.task.service.IUserService;
import org.example.task.utils.JwtUtil;
import org.example.task.utils.RedisUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final AuthenticationManager authenticationManager;
    private final RedisUtil redisUtil;
    private final JwtUtil jwtUtil;

    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("username", user.getUsername());
        String token = jwtUtil.generateToken(userId, userMap);
        redisUtil.setExSeconds("login" + userId, token, 3600);
        redisUtil.setExSeconds("auth" + userId, loginUser, 3600);
//        redisUtil.setEx("login" + userId, token, 3600);
//        redisUtil.setEx("auth" + userId, loginUser, 3600);
        lambdaUpdate().eq(User::getUserId, userId).set(User::getLastLoginTime, LocalDateTime.now()).update();
        return token;
    }

    @Override
    public boolean logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getUserId();
        return redisUtil.delete("login" + userId) && redisUtil.delete("auth" + userId);
    }

    @Override
    public PageDTO<UserPageVO> getUserPage(UserPageQuery userPageQuery) {
        Page<User> p = userPageQuery.toPage();
        lambdaQuery().eq(userPageQuery.getUsername() != null, User::getUsername, userPageQuery.getUsername())
                .eq(userPageQuery.getRealName() != null, User::getRealName, userPageQuery.getRealName())
                .eq(userPageQuery.getDeptId() != null, User::getDeptId, userPageQuery.getDeptId())
                .page(p);
        return PageDTO.of(p, UserPageVO.class);
    }
}
